package business

import (
	"errors"
	"vueBasic/app/admin/filter"
	"vueBasic/app/common/model"
	"vueBasic/extend/conv"
)

var AdminuserB = new(adminuserBus)

type adminuserBus struct {
}

// 列表
func (*adminuserBus) GetPageList(req *filter.AdminAdminuserReq) (any, int64, error) {
	userList, count, err := model.AdminUserM.GetList(req)
	list := make([]*filter.AdminAdminuserListRes, 0)
	for _, v := range userList {
		list = append(list, &filter.AdminAdminuserListRes{
			Id:            v.Id,
			Username:      v.Username,
			Nickname:      v.Nickname,
			Status:        v.Status,
			Mobile:        v.Mobile,
			Email:         v.Email,
			Qq:            v.Qq,
			RoleName:      v.Role.Title,
			AddTime:       conv.DateTime(v.AddTime),
			LastLoginTime: conv.DateTime(v.LastLoginTime),
		})
	}
	return list, count, err
}

func (*adminuserBus) GetFieldList() any {
	where := "1=1"
	roleList, _, _ := model.RoleM.GetList(where, 1, 100)
	list := make([]map[string]interface{}, 0)
	for _, v := range roleList {
		list = append(list, map[string]interface{}{
			"key": v.Title,
			"val": v.Id,
		})
	}
	return list
}

func (*adminuserBus) Add(req *filter.AdminAdminuserAddReq) (uint, error) {
	//判断该角色是否存在
	checkUser, _ := model.AdminUserM.GetAdminByUsername(req.Username)
	if checkUser != nil {
		return 0, errors.New("用户名已存在！")
	}
	res, err := model.AdminUserM.Add(req)
	if err != nil {
		return 0, err
	}
	return res, nil
}

func (*adminuserBus) GetUpdateInfo(req *filter.AdminAdminuserGetUpdateInfoReq) (any, error) {
	info, err := model.AdminUserM.GetAdminById(req)
	if err != nil {
		return nil, errors.New("用户不存在")
	}
	return info, nil
}

func (*adminuserBus) Update(req *filter.AdminAdminuserUpdateReq) (uint, error) {
	res, err := model.AdminUserM.Update(req)
	if err != nil {
		return 0, errors.New("更新失败")
	}
	return res, nil
}

func (*adminuserBus) UpdateExt(req map[string]interface{}) error {
	if conv.Int(req["id"]) == 1 {
		return errors.New("超级管理员禁止操作")
	}
	err := model.AdminUserM.UpdateExt(req)
	if err != nil {
		return errors.New("更新失败")
	}
	return nil
}

func (*adminuserBus) Delete(req *filter.AdminAdminuserDeleteReq) (uint, error) {
	ids := conv.Slice(req.Id)
	if len(ids) > 1 {
		return 0, errors.New("禁止批量删除")
	}
	if conv.Int(req.Id) == 1 {
		return 0, errors.New("超级管理员禁止删除")
	}
	res, err := model.AdminUserM.Delete(ids)
	if err != nil {
		return 0, errors.New("删除失败")
	}
	return res, nil
}

func (*adminuserBus) ResetPwd(req *filter.AdminAdminuserResetPwdReq) error {
	err := model.AdminUserM.ResetPwd(req)
	if err != nil {
		return errors.New("删除失败")
	}
	return nil
}
